import React, { Component } from 'react';
import { Button, Card, Divider, Form, Image, Input, List, message, Progress, Space, Spin, Upload } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { Store, ValidateErrorEntity } from 'rc-field-form/lib/interface'
import { devRes, getRes, prodRes } from '../../configFile';
import ManuForDeviceSelect from '../AddDevice/ManuForDeviceSelect';
import { queryManufacturer, searchManufacturer } from '../../requests/Manufacturer';
import DataCategory from '../../types/DataCategory';
import {
    addDeviceAttachment,
    addDevicePicture,
    addDeviceStereoPicture,
    checkDeviceAttachment,
    checkDevicePicture,
    checkDeviceStereoPicture,
    deleteDeviceAttachment,
    deleteDeviceData,
    deleteDevicePicture,
    deviceAdminModifyDevice,
    queryAttachment,
    queryCategory,
    queryDeviceInfo,
    queryDevicePictures,
    selectDeviceCover,
    supervisorModifyDevice,
    uploadTwoDimensionalData
} from '../../requests/Device';
import DeviceData from '../../types/DeviceData'
import DeviceAdminForDevice from '../AddDevice/DeviceAdminForDevice';
import { searchUser } from '../../requests/supervisor';
import DataCategoryForDevice from '../AddDevice/DataCategoryForDevice';
import DataType from '../../types/DataType';
import SELECTtoFill from '../AddDevice/SELECTtoFill';
import FiletoFill from '../AddDevice/FiletoFill';
import Axios from 'axios';
import { UploadOutlined } from '@ant-design/icons';
import { UploadFile } from 'antd/lib/upload/interface';
import { RouteComponentProps, withRouter } from 'react-router-dom';
import Device from '../../types/Device';
import ButtonGroup from 'antd/lib/button/button-group';
import SELECTtoModify from './SELECTtoModify';
import AttachmentInfo from '../../types/AttachmentInfo';
import PictureInfo from '../../types/PictureInfo';
import { RootState } from "../../reducers";
import { connect, ConnectedProps } from "react-redux";
import UserType from '../../types/UserType';
import ManufacturerInfo from '../../types/ManufacturerInfo';

interface IProps extends ConnectedProps<typeof connector>, RouteComponentProps<{ deviceID: string }> {
}

interface IState {
    attachProgress: number
    stereoProgress: number
    modifiedCates: number[]
    existedCates: DataCategory[]
    existedDeviceData: DeviceData[]
    deviceInfo: Device | undefined
    manufacturerID: number
    isLoading: boolean
    addedDataCategory: DataCategory[]
    textDeviceData: DeviceData[]
    selectDeviceData: DeviceData[]
    twoDimensionalDeviceData: DeviceData[]
    deviceAdminID?: number
    twoDFile: { file: File, cateID: number }[]
    attachFileList: UploadFile<any>[]
    pictureFileList: UploadFile<any>[]
    existedAttachments: AttachmentInfo[]
    existedPictures: PictureInfo[]
    stereoPictureFileList: UploadFile<any>[]
    initManuName: string   //修改前厂商名称
}

class SpecificModifyDevice extends Component<IProps, IState> {
    async componentDidMount() {
        //从链接提取设备信息
        const deviceID = Number.parseInt(this.props.match.params.deviceID);

        if (!deviceID) {
            message.error("设备信息错误");
            return;
        }

        //请求设备信息
        const deviceRes = getRes(await queryDeviceInfo(deviceID));
        if (!deviceRes.isSuccessful) {
            message.error(deviceRes.message);
            return;
        }

        //请求设备附件
        await this.getAttachment();
        //请求设备图片
        await this.getPictures();


        //设置设备基本信息
        this.setState({
            deviceInfo: deviceRes.data.device,
            existedDeviceData: deviceRes.data.deviceDataList
        });

        //设置表单默认值
        const { deviceInfo } = this.state;

        //请求初始厂商名称
        const initManuInfo: ManufacturerInfo = getRes(await queryManufacturer(deviceInfo?.manufacturerID || 2)).data
        this.setState({ initManuName: initManuInfo.manufacturerName })

        this.formRef.current?.setFieldsValue({
            deviceAdmin: deviceInfo?.userID,
            manu: { label: this.state.initManuName, value: deviceInfo?.manufacturerID },    //自定义表单控件，返回的值在一个对象中，提交表单时需要取出id
            deviceName: deviceInfo?.deviceName,
        })
        //并发请求数据类型
        const { existedDeviceData } = this.state;
        const res: Array<devRes | prodRes> = await Axios.all(existedDeviceData.map(item => queryCategory(item.categoryID)));
        for (let i = 0; i < res.length; i++) {
            if (!getRes(res[i]).isSuccessful) {
                message.error("数据类型请求失败" + getRes(res[i]).message)
                this.setState({ isLoading: false })
                return;
            }
        }
        //设置已有数据类型
        this.setState({
            existedCates: res.map(item => getRes(item).data),
            addedDataCategory: res.map(item => getRes(item).data)
        })

        this.setState({ isLoading: false })
    }

    formRef = React.createRef<FormInstance>()

    constructor(props: IProps) {
        super(props)
        this.state = {
            initManuName: "",
            attachProgress: 0,
            stereoProgress: 0,
            stereoPictureFileList: [],
            existedPictures: [],
            existedAttachments: [],
            modifiedCates: [],
            existedCates: [],
            existedDeviceData: [],
            deviceInfo: undefined,
            pictureFileList: [],
            attachFileList: [],
            addedDataCategory: [],
            manufacturerID: -1,
            isLoading: true,
            textDeviceData: [],
            selectDeviceData: [],
            twoDimensionalDeviceData: [],
            twoDFile: []
        }
    }

    layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
    };
    tailLayout = {
        wrapperCol: { offset: 4 },
    };

    //获取已有图片
    getPictures = async () => {
        try {
            const picture = getRes(await queryDevicePictures(Number.parseInt(this.props.match.params.deviceID)));
            if (!picture.isSuccessful) {
                message.error("图片获取失败" + picture.message);
            } else {
                this.setState({
                    existedPictures: picture.data
                })
            }
        } catch (err) {
            message.error(err.toString());
        }
    }
    //获取已有附件
    getAttachment = async () => {
        try {
            const attach = getRes(await queryAttachment(Number.parseInt(this.props.match.params.deviceID)));
            if (!attach.isSuccessful) {
                message.error("附件获取失败" + attach.message);
            } else {
                this.setState({
                    existedAttachments: attach.data
                })
            }
        } catch (err) {
            message.error(err.toString());
        }
    }

    //设置设备封面
    setDeviceCover = async (pictureID: number) => {
        try {
            const attach = getRes(await selectDeviceCover(Number.parseInt(this.props.match.params.deviceID), pictureID));
            if (!attach.isSuccessful) {
                message.error("封面设置失败！" + attach.message);
            } else {
                message.success("封面设置成功")
            }
        } catch (err) {
            message.error(err.toString());
        }
    }

    //删除已有的图片
    deleteExistedPicture = async (fileID: number) => {
        try {
            this.setState({ isLoading: true });
            if (!this.state.deviceInfo) {
                message.error("设备获取错误");
                return;
            }
            const fileIDList = [];
            fileIDList.push(fileID);
            const deleteRes = getRes(await deleteDevicePicture(this.state.deviceInfo.deviceID, fileIDList));
            if (!deleteRes.isSuccessful) {
                message.error("图片删除失败");
            }
            //刷新附件列表
            await this.getPictures();
            this.setState({ isLoading: false });
        } catch (err) {
            message.error(err.toString());
        } finally {
            this.setState({ isLoading: false });
        }
    }
    //删除已有的附件
    deleteExistedAttachment = async (fileID: number) => {
        try {
            this.setState({ isLoading: true });
            if (!this.state.deviceInfo) {
                message.error("设备获取错误");
                return;
            }
            const fileIDList = [];
            fileIDList.push(fileID);
            const deleteRes = getRes(await deleteDeviceAttachment(this.state.deviceInfo.deviceID, fileIDList));
            if (!deleteRes.isSuccessful) {
                message.error("附件删除失败");
            }
            //刷新附件列表
            await this.getAttachment();
            this.setState({ isLoading: false });
        } catch (err) {
            message.error(err.toString());
        } finally {
            this.setState({ isLoading: false });
        }
    }

    //上传二维数据（需要上传的，即修改或新加）
    uploadTwoDFunc = async (deviceID: number) => {

        //需要上传的twoD
        const neededTwoD = this.state.twoDFile.filter(
            item =>
                (this.state.modifiedCates.indexOf(item.cateID) !== -1)
                ||
                (this.state.addedDataCategory.map(itemCate => itemCate.dataCategoryID).indexOf(item.cateID) !== -1
                    &&
                    (this.state.existedCates.map(itemCate => itemCate.dataCategoryID).indexOf(item.cateID) === -1)
                ))    //在修改过的 或 在added不在existed中的

        const res: Array<devRes | prodRes> = await Axios.all(neededTwoD.map(item => uploadTwoDimensionalData(item.file, deviceID, item.cateID)))
        let flag: boolean = true;
        res.forEach(item => {
            if (!getRes(item).isSuccessful) {
                flag = false;
            }
        })
        return flag;
    }

    //是否是新加或更改
    ifNewlyAdded = (dataCate: DataCategory): boolean => {
        return !this.state.existedCates.map(item => item.dataCategoryID).includes(dataCate.dataCategoryID)
    }
    ifModified = (dataCate: DataCategory): boolean => {
        return this.state.modifiedCates.includes(dataCate.dataCategoryID)
    }
    ifNewlyAddedOrModified = (dataCate: DataCategory): boolean => {
        return this.ifModified(dataCate) || this.ifNewlyAdded(dataCate);
    }


    //设置3d图片上传进度条
    setStereoUploadProgress = (progress: any) => {
        this.setState({
            stereoProgress: (progress.loaded / progress.total) * 100
        })
    }
    //设置附件上传进度条
    setAttachmentUploadProgress = (progress: any) => {
        this.setState({
            attachProgress: (progress.loaded / progress.total) * 100
        })
    }

    //输入合法函数
    onFinish: (values: Store) => void = async values => {
        values.manu = values.manu.value;  //从自定义表单控件的返回中提取数据
        this.state.addedDataCategory.forEach(item => {
            //修改过的加入textDeviceData
            if (item.dataType === DataType.TEXT
                &&
                this.ifNewlyAddedOrModified(item)
            ) {
                this.state.textDeviceData.push({
                    dataValue: values[item.dataCategoryID],
                    categoryID: item.dataCategoryID
                })
            }
            //修改过的加入selectDeviceData
            if (item.dataType === DataType.SELECT
                &&
                this.ifNewlyAddedOrModified(item)
            ) {
                this.state.selectDeviceData.push({
                    dataValue: values[item.dataCategoryID],
                    categoryID: item.dataCategoryID
                })
            }
            this.setState({ ...this.state })
        })

        const { textDeviceData, selectDeviceData } = this.state
        const { deviceID } = this.state.deviceInfo as Device;
        try {
            this.setState({ isLoading: true })
            if (this.state.deviceInfo) {

                const res = this.props.userType === UserType.SUPERVISOR ?
                    getRes(await supervisorModifyDevice(deviceID, values.deviceName, values.manu, textDeviceData.concat(selectDeviceData), values.deviceAdmin))
                    :
                    getRes(await deviceAdminModifyDevice(deviceID, values.deviceName, values.manu, textDeviceData.concat(selectDeviceData)))
                //清空已添加
                this.setState({
                    textDeviceData: [],
                    selectDeviceData: []
                })
                //添加确认后发送二维数据
                if (!res.isSuccessful) {
                    message.error("设备数据修改失败" + res.message)
                    return;
                }
                //并发发送二维数据
                if (await this.uploadTwoDFunc(deviceID)) {
                    message.success("设备数据修改成功")
                } else {
                    message.error("二维数据添加失败")
                }
            } else {
                message.error("设备获取错误");
                return;
            }

            //发送附件
            const { attachFileList, pictureFileList, stereoPictureFileList } = this.state
            //上传附件检测
            if (attachFileList.length > 0) {
                const fileNames = attachFileList.map(item => item.name)
                const fileSizes = attachFileList.map(item => item.size)
                const attachCheck = getRes(await checkDeviceAttachment(deviceID, fileNames, fileSizes))
                if (attachCheck.isSuccessful) {
                    message.success("附件允许上传")
                    //上传附件                  TODO:类型as unknown，从UploadFile<any>转换到File
                    const fileList: File[] = attachFileList as unknown as File[];
                    const addAttach = getRes(await addDeviceAttachment(deviceID, fileList, this.setAttachmentUploadProgress))
                    if (addAttach.isSuccessful) {
                        message.success("附件上传成功")
                        await this.getAttachment();
                        this.setState({ attachFileList: [] });
                    } else {
                        message.error("附件上传失败" + addAttach.message)
                    }
                } else {
                    message.error("附件上传检测失败" + attachCheck.message)
                }
            }
            //发送图片
            //上传图片检测
            if (pictureFileList.length > 0) {
                const pictureCheck = getRes(await checkDevicePicture(deviceID));
                if (pictureCheck.isSuccessful) {
                    message.success("图片允许上传")
                    //上传图片                  TODO:类型as unknown，从UploadFile<any>转换到File
                    const fileList: File[] = pictureFileList as unknown as File[];
                    const addPicture = getRes(await addDevicePicture(deviceID, fileList))
                    if (addPicture.isSuccessful) {
                        message.success("图片上传成功")
                        this.setState({ pictureFileList: [] })  //清空
                    } else {
                        message.error("图片上传失败" + addPicture.message)
                    }
                } else {
                    message.error("图片上传检测失败" + pictureCheck.message)
                }
            }

            //发送3D图片
            if (stereoPictureFileList.length > 0) {
                const fileNames = stereoPictureFileList.map(item => item.name)
                const fileSizes = stereoPictureFileList.map(item => item.size)
                const stereoPictureCheck = getRes(await checkDeviceStereoPicture(deviceID, fileNames, fileSizes))
                if (stereoPictureCheck.isSuccessful) {
                    message.success("3D图片允许上传")
                    //上传3D图片                  TODO:类型as unknown，从UploadFile<any>转换到File
                    const fileList: File[] = stereoPictureFileList as unknown as File[];
                    const addStereoPicture = getRes(await addDeviceStereoPicture(deviceID, fileList, this.setStereoUploadProgress))
                    if (addStereoPicture.isSuccessful) {
                        message.success("3D图片上传成功")
                        this.setState({ stereoPictureFileList: [] })
                    } else {
                        message.error(addStereoPicture.message)
                    }
                } else {
                    message.error("3D图片上传检测失败" + stereoPictureCheck.message)
                }
            }
        } catch (err) {
            message.error(err.toString())
        } finally {
            this.setState({
                isLoading: false,
                stereoProgress: 0,
                attachProgress: 0,
            })
        }

    }

    onFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };

    //模态框选中数据类型回调函数    (不允许删除已存在数据类型)
    setSelectedCate = (arr: Array<DataCategory>) => {
        //保证不删除existed
        this.state.existedCates.forEach(eachExisted => {
            if (!arr.map(item => item.dataCategoryID).includes(eachExisted.dataCategoryID)) {   //不包括existed
                arr.push(eachExisted);
            }
        });
        this.setState({
            addedDataCategory: arr
        });
    }

    //删除之前已存在的数据类型
    deleteExistedCate = async (cateID: number) => {
        this.setState({ isLoading: true });
        const { deviceID } = this.state.deviceInfo as Device;
        //TODO发送删除请求
        try {
            const res = getRes(await deleteDeviceData(deviceID, cateID));
            if (!res.isSuccessful) {
                message.error("数据删除失败！");
                this.setState({ isLoading: false });
                return;
            } else {
                message.success("数据删除成功");
            }
        } catch (err) {
            message.error(err.toString());
            return;
        } finally {
            this.setState({ isLoading: false });
        }

        //设置渲染
        this.setState({
            existedCates: this.state.existedCates.filter(item => item.dataCategoryID !== cateID),
            addedDataCategory: this.state.addedDataCategory.filter(item => item.dataCategoryID !== cateID),
            modifiedCates: this.state.modifiedCates.filter(item => item !== cateID)
        })
    }

    //删除已选中的新增数据类型
    deleteAddedCate = (cateID: number) => {
        this.setState({
            addedDataCategory: this.state.addedDataCategory.filter(item => item.dataCategoryID !== cateID)
        })
    }

    //二维数据获得文件
    getFile = (file: File, cateID: number) => {
        this.setState({ twoDFile: this.state.twoDFile.filter(item => item.cateID !== cateID) });      //覆盖之前上传
        this.state.twoDFile.push({ file, cateID });
        this.setState({ ...this.state });
    }

    //移除附件
    attachRemove = (file: UploadFile<any>) => {
        //处理列表
        this.setState(state => {
            const index = state.attachFileList.indexOf(file);
            const newFileList = state.attachFileList.slice();
            newFileList.splice(index, 1);
            return {
                attachFileList: newFileList,
            };
        });
    }
    //移除图片
    pictureRemove = (file: UploadFile<any>) => {
        //处理列表
        this.setState(state => {
            const index = state.pictureFileList.indexOf(file);
            const newFileList = state.pictureFileList.slice();
            newFileList.splice(index, 1);
            return {
                pictureFileList: newFileList,
            };
        });
    }
    //移除3D图片
    stereoPictureRemove = (file: UploadFile<any>) => {
        //处理列表
        this.setState(state => {
            const index = state.stereoPictureFileList.indexOf(file);
            const newFileList = state.stereoPictureFileList.slice();
            newFileList.splice(index, 1);
            return {
                stereoPictureFileList: newFileList,
            };
        });
    }

    //附件上传前加入文件列表
    beforeAttachUpload = (file: UploadFile<any>) => {
        if (this.state.attachFileList.map(item => item.name).includes(file.name)) {
            message.error("已加入同名文件 " + file.name);
            return false;
        }
        this.setState(state => ({
            attachFileList: [...state.attachFileList, file],
        }));
        return false;
    }
    //图片上传前加入文件列表
    beforePictureUpload = (file: UploadFile<any>) => {
        if (this.state.pictureFileList.map(item => item.name).includes(file.name)) {
            message.error("已加入同名文件 " + file.name);
            return false;
        }
        this.state.pictureFileList.push(file);
        this.setState({ ...this.state });
        return false;
    }
    //3D图片上传前加入文件列表
    beforeStereoPictureUpload = (file: UploadFile<any>) => {
        if (this.state.stereoPictureFileList.map(item => item.name).includes(file.name)) {
            message.error("已加入同名文件 " + file.name);
            return false;
        }
        this.state.stereoPictureFileList.push(file);
        this.setState({ ...this.state });
        return false;
    }

    //增加修改的数据类型
    addModifiedDataCate = (cateID: number) => {
        console.log("增加", cateID);
        if (!this.state.modifiedCates.includes(cateID)) {
            this.state.modifiedCates.push(cateID);
        }
        this.setState({ ...this.state })
    }

    //放弃修改
    abortModify = (cateID: number) => {
        const index = this.state.modifiedCates.indexOf(cateID);
        this.state.modifiedCates.splice(index, 1);
        this.setState({ ...this.state })
    }

    render() {
        const { addedDataCategory } = this.state
        return (
            <div>
                <Spin size='large' spinning={this.state.isLoading}>
                    <Card title={`编辑设备 ${this.state.deviceInfo?.deviceName}`}>

                        <Form
                            onFinishFailed={this.onFinishFailed}
                            onFinish={this.onFinish}
                            ref={this.formRef}
                            {...this.layout}
                            name="modifyDevice"
                        >

                            <Form.Item
                                label="设备名称"
                                name="deviceName"
                                rules={[
                                    {
                                        required: true,
                                        message: '设备名称必填',
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>

                            {this.props.userType === UserType.SUPERVISOR ?
                                (
                                    <Form.Item
                                        label="指定管理员（可选）"
                                        name="deviceAdmin"
                                        rules={[{ required: false }]}
                                    >
                                        <DeviceAdminForDevice queryFunc={searchUser} />
                                    </Form.Item>
                                )
                                :
                                ''
                            }

                            < Form.Item
                                label="厂商名称"
                                name="manu"
                                rules={[{ required: true, message: "厂商必填" }]}
                            >
                                <ManuForDeviceSelect queryFunc={searchManufacturer} />
                            </Form.Item>


                            <Form.Item label="新增附件">
                                <Upload
                                    multiple={true}
                                    onRemove={this.attachRemove}
                                    beforeUpload={this.beforeAttachUpload}
                                    fileList={this.state.attachFileList}
                                >
                                    <Button icon={<UploadOutlined />}>选择附件</Button>
                                </Upload>
                                <Progress percent={this.state.attachProgress} style={this.state.attachProgress === 0 ? { display: 'none' } : {}} />
                            </Form.Item>

                            <Form.Item label="新增图片">
                                <Upload
                                    multiple={true}
                                    onRemove={this.pictureRemove}
                                    beforeUpload={this.beforePictureUpload}
                                    fileList={this.state.pictureFileList}
                                    accept='image/*'
                                >
                                    <Button icon={<UploadOutlined />}>选择图片</Button>
                                </Upload>
                            </Form.Item>

                            <Form.Item
                                label="更新3D图片"
                                extra="请上传多张图片或其压缩包，以一定角度递增拍摄并命名，如&quot;1.jpg&quot;、&quot;2.jpg&quot;等"
                            >
                                <Upload
                                    multiple={true}
                                    onRemove={this.stereoPictureRemove}
                                    beforeUpload={this.beforeStereoPictureUpload}
                                    fileList={this.state.stereoPictureFileList}
                                    accept='image/*,
                                     application/x-gzip,
                                     application/x-bzip2,
                                     application/zip,
                                     application/x-rar,
                                     application/x-tar,
                                     application/x-7z-compressed'
                                >
                                    <Button icon={<UploadOutlined />}>选择图片</Button>
                                </Upload>
                                <Progress percent={this.state.stereoProgress} style={this.state.stereoProgress === 0 ? { display: 'none' } : {}} />
                            </Form.Item>

                            <Card title="设备参数" bordered={false}
                                extra={<DataCategoryForDevice key={this.state.addedDataCategory.length}
                                    propCate={this.state.addedDataCategory}
                                    setSelectedCate={this.setSelectedCate} />}>
                                {
                                    //不修改的数据类型
                                    addedDataCategory.map(item => {
                                        if (!this.ifNewlyAddedOrModified(item)) {
                                            return (
                                                <List.Item
                                                    actions={[
                                                        <h3>类型：{item.dataType}</h3>,
                                                        <Button
                                                            onClick={this.addModifiedDataCate.bind(this, item.dataCategoryID)}
                                                        >修改</Button>
                                                    ]}
                                                    key={item.dataCategoryID}
                                                >
                                                    {item.dataCategoryName}
                                                </List.Item>
                                            )
                                        }
                                        return undefined;
                                    })
                                }
                                {/* 修改的 */}
                                {
                                    addedDataCategory.map(item => {
                                        if (this.ifModified(item)) {
                                            return (
                                                <Form.Item
                                                    labelCol={{ span: 4 }}
                                                    label={item.dataCategoryName}
                                                    name={item.dataCategoryID}
                                                    key={item.dataCategoryID}
                                                    rules={[{ required: true, message: "参数内容必填" }]}
                                                >
                                                    {
                                                        item.dataType === DataType.TEXT ?
                                                            (<Space>
                                                                <Input style={{ width: 400 }} placeholder="参数内容" />
                                                                <ButtonGroup>
                                                                    <Button
                                                                        danger
                                                                        onClick={this.deleteExistedCate.bind(this, item.dataCategoryID)}
                                                                    >删除类型</Button>
                                                                    <Button
                                                                        onClick={this.abortModify.bind(this, item.dataCategoryID)}
                                                                    >放弃修改</Button>
                                                                </ButtonGroup>
                                                            </Space>)
                                                            :
                                                            item.dataType === DataType.SELECT ?
                                                                (<SELECTtoModify
                                                                    propCate={item}
                                                                    abortModify={this.abortModify}
                                                                    deleteExistedCate={this.deleteExistedCate}
                                                                />)
                                                                :
                                                                (<Space>
                                                                    <FiletoFill
                                                                        getFile={this.getFile}
                                                                        cateID={item.dataCategoryID} />
                                                                    <ButtonGroup>
                                                                        <Button
                                                                            danger
                                                                            onClick={this.deleteExistedCate.bind(this, item.dataCategoryID)}
                                                                        >删除类型</Button>
                                                                        <Button
                                                                            onClick={this.abortModify.bind(this, item.dataCategoryID)}
                                                                        >放弃修改</Button>
                                                                    </ButtonGroup>
                                                                </Space>)
                                                    }
                                                </Form.Item>
                                            )
                                        }
                                        return null;
                                    })
                                }

                                {/* 新增的 */}
                                {
                                    addedDataCategory.map(item => {
                                        if (this.ifNewlyAdded(item)) {
                                            return (
                                                <Form.Item
                                                    labelCol={{ span: 4 }}
                                                    label={item.dataCategoryName}
                                                    name={item.dataCategoryID}
                                                    key={item.dataCategoryID}
                                                    rules={[{ required: true, message: "参数内容必填" }]}
                                                >
                                                    {
                                                        item.dataType === DataType.TEXT ?
                                                            (
                                                                <Space>
                                                                    <Input style={{ width: 400 }} placeholder="参数内容" />
                                                                    <Button danger
                                                                        onClick={this.deleteAddedCate.bind(this, item.dataCategoryID)}>删除</Button>
                                                                </Space>
                                                            )
                                                            :
                                                            item.dataType === DataType.SELECT ?
                                                                (
                                                                    <SELECTtoFill propCate={item}
                                                                        deleteAddedCate={this.deleteAddedCate} />
                                                                )
                                                                :
                                                                (
                                                                    <Space>
                                                                        <FiletoFill getFile={this.getFile}
                                                                            cateID={item.dataCategoryID} />
                                                                        <Button danger
                                                                            onClick={this.deleteAddedCate.bind(this, item.dataCategoryID)}>删除</Button>
                                                                    </Space>
                                                                )
                                                    }

                                                </Form.Item>

                                            )
                                        }
                                        return null;
                                    })
                                }

                            </Card>

                            <Form.Item {...this.tailLayout}>
                                <Button type="primary" htmlType="submit" size="large">
                                    确认修改
                                </Button>
                            </Form.Item>
                        </Form>


                        <Divider
                            orientation="left"
                            style={{ fontWeight: "bold" }}
                        >
                            已有附件列表
                        </Divider>
                        <List
                            bordered
                            dataSource={this.state.existedAttachments}
                            renderItem={item => (
                                <List.Item>
                                    <Space>
                                        <a target="_blank" rel="noopener noreferrer" href={item.filePath}>{item.fileName}</a>
                                    </Space>
                                    <Button
                                        onClick={this.deleteExistedAttachment.bind(this, item.attachmentID)}>删除</Button>
                                </List.Item>
                            )}
                        />

                        <Divider
                            orientation="left"
                            style={{ fontWeight: "bold" }}
                        >
                            已有图片列表
                        </Divider>
                        <List
                            bordered
                            dataSource={this.state.existedPictures}
                            renderItem={item => (
                                <List.Item>
                                    <Space>
                                        <Image width={100} src={item.filePath} />
                                    </Space>
                                    <ButtonGroup>
                                        <Button onClick={this.setDeviceCover.bind(this, item.pictureID)}>设为封面</Button>
                                        <Button
                                            onClick={this.deleteExistedPicture.bind(this, item.pictureID)}>删除</Button>
                                    </ButtonGroup>
                                </List.Item>
                            )}
                        />
                    </Card>
                </Spin>
            </div >
        )
    }
}
//connect加入props
const mapStateToProps = (state: RootState) => {
    return {
        userID: state.loginReducers.userID,
        userType: state.loginReducers.userType
    }
}
const connector = connect(mapStateToProps);

export default withRouter(connector(SpecificModifyDevice))